﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using PRScreenWithKinect.Model;
using System.Windows.Threading;
using System.Timers;

namespace PRScreenWithKinect
{
	/// <summary>
	/// Interaction logic for BillBoard.xaml
	/// </summary>
	public partial class BillBoard : UserControl,UserControlInterfaceForGesture
	{
        const int PERIOD_AUTOPLAY_TIME = 5*1000;
        private ArrayList controllerElement;
        private UIElement hitElement = null;
        private UIElement hittedElement = null;
        private Double focusOpacity = 0.7, defaultOpacity = 0.3;
        private SolidColorBrush focusColor = Brushes.Orange, defaultColor = Brushes.White;
        private int pageIndex = 0;
        private ListBox[] ar;
        private int mainController;
        private Timer autoplay_counter;
        private int numOfContent = 0;
		public BillBoard()
		{
			this.InitializeComponent();
            // Add Menu to controllerElement ;s
            controllerElement = new ArrayList();
            controllerElement.Add(CloseZoom);

            mainController = controllerElement.Count;

            /// Load Data
            loadDataFromJSON();
            autoplay_counter = new Timer();
            autoplay_counter.Interval = PERIOD_AUTOPLAY_TIME;
            autoplay_counter.Enabled = false;
            autoplay_counter.Elapsed += new ElapsedEventHandler(autoplay_counter_Elapsed);

            Content_Zoom.Visibility = Visibility.Hidden;
            
		}

        

        void autoplay_counter_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (numOfContent != 0)
            {
                pageBulletStack.Dispatcher.Invoke(new Action(delegate()
                {
                    pageBulletStack.Children[pageIndex].Opacity = defaultOpacity;
                    pageIndex = (pageIndex + 1) % numOfContent;
                    pageBulletStack.Children[pageIndex].Opacity = focusOpacity;
                }));
         
                scrollView.Dispatcher.Invoke(new Action(delegate()
                {
                    scrollView.ScrollToPosition(scrollView.Width * pageIndex, 0);
                }));
            
            }
 

        }
        public void startAutoPlay()
        {
          //  pageBulletStack.Visibility = Visibility.Hidden;
            autoplay_counter.Start();
           
        }
        public void stopAutoPlay()
        {
           // pageBulletStack.Visibility = Visibility.Visible;
            autoplay_counter.Stop();
        }
        private void loadDataFromJSON()
        {
            ///// Load Data from Json
            pageIndex = 0;
            //// Image (W,H) = 548,863
            int wView = 540;
            int hView = 863;
           // Thickness b = new Thickness(0, 0, 0, 0);

            DataFactory datafactory = DataFactory.Instance;

            List<BillboardModel> billboards = datafactory.getBillboardModel();
             numOfContent = billboards.Count;
          //  Console.WriteLine("Billboard DATA : " + numOfContent);

            for (int i = 0; i < numOfContent; i++)
            {
                DataGrid d = new DataGrid();

                d.Template = (ControlTemplate)this.Resources["MyDataTemplate"];
              //billboards[i].poster.Dispatcher.Invoke(new Action(delegate()
              //  {
                //Dispatcher.Invoke(
                //DispatcherPriority.Normal,
                //new Action(() =>
                //{
                BillboardModel b = billboards[i];
                b.poster = new BitmapImage(new Uri(b.imagePath));
                    d.DataContext =b;
                    d.Height = hView;
                    d.Width = wView;
                    d.Background = Brushes.Cyan;
                    viewer.Children.Add(d);

                    d.Loaded += new RoutedEventHandler(d_Loaded);
                //}));
         
                //}));
            
            }

            /// Create Page Bullet with parameter count_page
            createPageBullet(numOfContent);
        }

        void d_Loaded(object sender, RoutedEventArgs e)
        {
            DataGrid d = (DataGrid)sender;
            BillboardModel b = (BillboardModel)d.DataContext;
             Canvas g = (Canvas)d.Template.FindName("moreCanvas", d);
            if (b.newsObj == null)
            {
                // Grid g = (Grid)d.Template.Resources.C
                //Grid g = (Grid)VisualTreeHelper.GetChild(d.TemplatedParent, 0);
               
                //  Canvas c = (Canvas)g.Children[0];
                g.Visibility = Visibility.Hidden;
            }
            else
            {
                controllerElement.Add(g);
                
            }
        }
        private void createPageBullet(int n)
        {
            pageBulletStack.Children.RemoveRange(0, pageBulletStack.Children.Count);
            for (int i = 0; i < n; i++)
            {
                Ellipse myEllipse = new Ellipse();

                // Create a SolidColorBrush with a red color to fill the 
                // Ellipse with.

                myEllipse.Fill = Brushes.Gray;
                if (i == 0)
                {
                    myEllipse.Opacity = focusOpacity;
                }
                else
                {
                    myEllipse.Opacity = defaultOpacity;
                }



                // Set the width and height of the Ellipse.
                myEllipse.Width = 20;
                myEllipse.Height = 20;
                myEllipse.Margin = new Thickness(5, 0, 0, 0);
                //   Console.WriteLine("Add Bullet");
                pageBulletStack.Children.Add(myEllipse);
            }


        }
      


        public void finishHold()
        {
            if (hitElement.GetType() == typeof(Canvas))
            {
                Canvas c = (Canvas)hitElement;
                Grid g = (Grid)c.Parent;
               DataGrid dg = (DataGrid)g.TemplatedParent;
               BillboardModel b = (BillboardModel)dg.DataContext;
                zoomContent(b.newsObj);
            }
            else if (CloseZoom.Equals(hitElement))
            {
                closeZoom();
            }

            hittedElement = hitElement;
            hitElement = null;
        }


        public void swipeLeft()
        {
            doSwipe(Swipe.Left);
        }

        public void swipeRight()
        {
            doSwipe(Swipe.Right);
        }

        public void doSwipe(Swipe s)
        {

            if (s == Swipe.Left && pageIndex <(viewer.Children.Count -1))
            {



                pageIndex++;
                pageBulletStack.Children[pageIndex].Opacity = focusOpacity;
                pageBulletStack.Children[pageIndex - 1].Opacity = defaultOpacity;

            }
            else if (s == Swipe.Right && pageIndex > 0)
            {

                pageIndex--;
                pageBulletStack.Children[pageIndex].Opacity = focusOpacity;
                pageBulletStack.Children[pageIndex + 1].Opacity = defaultOpacity;

            }
            scrollView.ScrollToPosition(scrollView.Width * pageIndex, 0);

          //  Console.WriteLine("News(doSwipe) : " + pageIndex);
        }

        public void zoomContent(NewsModel n)
        {
            _headZoom.Text = n.headline;
            _subHeadZoom.Text = string.Format("{0} | {1}", n.dateTime, n.catagory);
            _contentZoom.Text = n.content;

            //throw new NotImplementedException();
            scrollView.Opacity = GlobalConfig.NON_FOCUS_OPACITY;

            Content_Zoom.Visibility = Visibility.Visible;
            
        }

        public void closeZoom()
        {
           // throw new NotImplementedException();
            Content_Zoom.Visibility = Visibility.Hidden;
            scrollView.Opacity = 1;
        }

        public bool hitTest(Point p, Window w)
        {

            Boolean isHit = false;
            if (this.IsLoaded)
            {
                foreach (UIElement c in controllerElement)
                {
                    Point RhandRelativePoint = c.TransformToAncestor(w).Transform(new Point(0, 0));
                    Point delta = new Point(p.X - RhandRelativePoint.X, p.Y - RhandRelativePoint.Y);
                    if (VisualTreeHelper.HitTest(c, delta) != null)
                    {
                        if (c.Equals(hitElement) && !c.Equals(hittedElement))
                        {
                            if (c.Equals(CloseZoom) && Content_Zoom.IsVisible)
                            {
                                return true;
                            }
                            else if (!Content_Zoom.IsVisible && !c.Equals(CloseZoom))
                            {
                                return true;
                            }
                        }
                        else
                        {
                            hitElement = c;
                            return false;

                        }
                    }
                }

            }
            return isHit;
        }
    }
}